package main

import (
	"fmt"
	"github.com/widuu/goini"
	"io/ioutil"
	"net/http"
	"os"
	"regexp"
	"strconv"
)

var (
	cUrlName   = "Url"
	cRegexName = "Regex"
	cCountName = "Count"
	cDebugName = "Debug"
)

func ReadConf() map[string]string {
	m := make(map[string]string, 10)
	conf := goini.SetConfig("./conf/conf.ini")
	m[cUrlName] = conf.GetValue("Setting", cUrlName)
	m[cRegexName] = conf.GetValue("Setting", cRegexName)
	m[cCountName] = conf.GetValue("Setting", cCountName)
	m[cDebugName] = conf.GetValue("Setting", cDebugName)
	return m
}

func main() {

	m := ReadConf()

	ptnContex := regexp.MustCompile(m[cRegexName])
	resp, err := http.Get(m[cUrlName])

	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()

	count, err := strconv.ParseInt(m[cCountName], 10, 64)

	body, err := ioutil.ReadAll(resp.Body)

	content := string(body)

	if m[cDebugName] == "true" {
		fmt.Print(content)
		file, err := os.Create("./save.txt")
		defer file.Close()
		if err == nil {
			file.Write(body)
		} else {
			fmt.Println(err)
		}
	}

	matches := ptnContex.FindAllStringSubmatch(content, 100)
	fmt.Println(len(matches))
	for i, item := range matches {
		fmt.Println("=====", i, "=====")
		for n := 0; n < int(count); n++ {
			fmt.Println(item[n+1])
		}
	}

}
